<?php

namespace App\Http\Controllers\Ajax;

use App\Models\BalanceRecord;
use App\Models\BirthdayPrerogativeGetRecord;
use App\Models\ContinueSigninRecord;
use App\Models\CreditsRecod;
use App\Models\MerchantTicket;
use App\Models\WxcardPrerogative;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;

class AboutUserController extends Controller
{
    /**
     * 获取会员二维码
     * @param UserRepository $UserRepository
     * @return string
     */
    public function getConsumeQrcodeText(UserRepository $userRepository)
    {
        $wxuser_mcard = $this->getSeesionWxuseMcard();
        //$user = Wxuser::find(29247);
        $str = url('/bind-phone').'/'.$wxuser_mcard->id_merchant.'?secret_param='.strrev(base64_encode(strrev($wxuser_mcard->card_no))).'&time='.time();

        //\Redis::set(base64_encode($user->id_wxuser),$str);

        return $this->response->array(['code'=>200,'msg'=>$str]);
    }

    /**
     * 获取积分记录列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getCreditsRecords()
    {
        $credits_records = $this->getSeesionWxuseMcard()->creditsRecords()->orderBy('created_at','desc')->paginate(10);

        $data = $credits_records->groupBy(function($item){
            return $item->created_at->year.'年'.$item->created_at->month.'月';
        });
        return view('user.list._credits_list',compact('data'));

    }

    /**
     * 获取余额明细
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getBalanceRecords()
    {
        $balance_records = $this->getSeesionWxuseMcard()->balanceRecords()->orderBy('created_at','desc')->paginate(10);

        $data = $balance_records->groupBy(function($item){
            return $item->created_at->year.'年'.$item->created_at->month.'月';
        });
        return view('user.list._balance_list',compact('data'));
    }

    /**
     * @param UserRepository $userRepository
     * @param Request $request
     * 获取当月打卡记录
     */
    public function monthClockRecord(UserRepository $userRepository,Request $request)
    {
        $month = $request->ymonth;//yyyy-mm

        //签到记录
        $month_records = $userRepository->getPunchClockByMonth($month);

        //获取签到时间表
        $record_time = $month_records->map(function($item){
            return date('Ymd',strtotime($item['created_at']));
        })->toArray();

        return $this->response->array(['code'=>200,'msg'=>$record_time]);
    }

    /**
     * 打卡
     * @param UserRepository $userRepository
     * @return mixed
     */
    public function punchClock(UserRepository $userRepository)
    {
        if($userRepository->isPunchClock())
            return $this->response->array(['code'=>403,'msg'=>'今日已经打过啦']);

        //打卡规则
        $rule = $userRepository->getFirstSigninShare();
        $new_record = $userRepository->punchClockByRule($rule);

        //达到连续签到要求
        if($new_record->times== $rule->sign_many){
            return $this->response->array(['code'=>203,'msg'=>'恭喜达到连续签到要求，连续签到奖可领取哦！','value'=>$rule->credits_one]);
        }

        return $this->response->array(['code'=>200,'msg'=>'签到成功','value'=>$rule->credits_one]);
    }

    /**
     * 领取连续打卡
     * @param UserRepository $userRepository
     * @return mixed
     */
    public function getContinuegGift(UserRepository $userRepository)
    {
        //获取最近一次打卡记录
        $recently_record = $userRepository->getRecentlyClockRecord();
        //打卡规则
        $rule = json_decode($recently_record->signin_rule,true);

        if($recently_record->created_at->toDateString() != now()->toDateString())
            return $this->response->array(['code'=>'403','msg'=>'不好意思，还不能领取']);

        if($recently_record->times*1<$rule['sign_many']*1)
            return $this->response->array(['code'=>'402','msg'=>'不好意思，还不能领取']);

        if(ContinueSigninRecord::where('id_signin_share_record',$recently_record->id)->first())
            return $this->response->array(['code'=>'205','msg'=>'不好意思，您已经领取过了']);

        $insert_data = [
            'id_wxuser_mcard'=>$this->getSeesionWxuseMcard()->id_wxuser_mcard,
            'id_merchant'=>session('web_merchant')->id_merchant,
            'id_signin_share_record'=>$recently_record->id,
            'credits'=>$rule['credits'],
            'id_tickets'=>$rule['ticket'],
            'cash'=>$rule['cash'],
            'created_at'=>now()->toDateTimeString(),
        ];

        $msg = '';
        if(isset($rule['credits']) && $rule['credits']>0) {
            $msg .= '积分 +'.$rule['credits'].';';
        }

        if(isset($rule['cash']) && $rule['cash']>0){
            $msg .= '余额 +'.$rule['cash'].';';
        }

        if(isset($rule['id_tickets']) && !empty($rule['id_tickets'])){
            $msg .= '卡券 +'.count(explode(',',$rule['id_tickets'])).'张;';
        }

        if($record = ContinueSigninRecord::create($insert_data)){

            return $this->response->array(['code'=>200,'msg'=>'领取成功,'.trim($msg,';'),'credits'=>$rule['credits']]);
        }

    }


    /**
     * 领取生日特权
     * @param Request $request
     * @return mixed
     */
    public function getBirthdayGift(Request $request)
    {
        if(substr(now()->toDateString(),5) != substr($this->getSeesionWxuseMcard()->member_optional_birthday,5))
            return $this->response->array(['code'=>'403','msg'=>'还未到领取时间:)']);

        $id = $request->id;

        $prerogative = WxcardPrerogative::find($id);

        if(!$prerogative) return $this->response->array(['code'=>'404','msg'=>'未找到奖品信息:)']);

        $insert_data = [
            'id_wxuser_mcard'=>$this->getSeesionWxuseMcard()->id_wxuser_mcard,
            'id_merchant'=>$this->getSeesionWxuseMcard()->id_merchant,
            'wxcard_phone'=>(int) $this->getSeesionWxuseMcard()->member_optional_telephone,
            'wxcard_name'=>$this->getSeesionWxuseMcard()->member_optional_name,
            'cash'=>$prerogative->cash,
            'credits'=>$prerogative->credits,
            'id_tickets'=>$prerogative->ticket,
        ];

        if(BirthdayPrerogativeGetRecord::create($insert_data)) return $this->response->array(['code'=>200,'msg'=>'领取成功']);

        return $this->response->array(['code'=>500,'msg'=>'领取失败']);

    }
}
